package utilities.event;

import hibernatesrc.billStream.AccommodatingRec;
import hibernatesrc.billStream.ConcreteBill;

import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import org.hibernate.Session;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;

import utilities.Updatable;
import utilities.utilities_components.SumUp;

public class RIDListener implements EventListener{
	private SumUp controller;
	private Updatable updateItem;
	
	public RIDListener( SumUp controller, Updatable updateItem ){
		this.controller = controller;
		this.updateItem = updateItem;
	}
	
	public void onEvent( Event event ){
		Calendar calendar = controller.getDate();
		updateItem.update( getData( calendar.get( Calendar.YEAR ), calendar.get( Calendar.MONTH ) ), session );
	}
	
	
	/*  "入账日期", "计天房单价", "天数", "金额",
	 *  "钟点房单价", "小时数", "金额", "总房款"*/
	private List getData(int year,int month, Session session ){
		List ret=new LinkedList();
		
		Calendar from=Calendar.getInstance();
		
		from.set(Calendar.YEAR,year);
		from.set(Calendar.MONTH,month);
		from.set(Calendar.DATE,1);
		Date fromTime=from.getTime();
		
		from.set(Calendar.MONTH,month+1);
		Date toTime=from.getTime();
		
		List bills=getBillByTime(fromTime,toTime,ConcreteBill.getClass());
		Iterator itr=bills.iterator();
		ConcreteBill temp=null;
		while(itr.hasNext()){
			temp=(ConcreteBill)itr.next();
			
			List col=new LinkedList();
			
			//basic info
			if(col.getCountByHour()){
				col.add(temp.getTimePay());
				Double price=temp.
						getAssociatedRoom().
						getRoomType().
						getPricePerHour();
				col.add(price);
			
				//number of days in room
				Iterator itr2=temp.getAccommodatingList().iterator();
				int days=0;
				while(itr2.hasNext()){
					AccommodatingRec currentRec=(AccommodatingRec)itr2.next();
					days+=(currentRec.getTimeTo().getTime()-currentRec.getTimeFrom().getTime())/86400;
				}
				col.add(days);
				col.add(price*days);
				col.add("");
				col.add("");
				col.add("");
			}else{
				col.add("");
				col.add("");
				col.add("");
				col.add(temp.getTimePay());
				Double price=temp.
						getAssociatedRoom().
						getRoomType().
						getPricePerDay();
				col.add(price);
			
				//number of days in room
				Iterator itr2=temp.getAccommodatingList().iterator();
				int days=0;
				while(itr2.hasNext()){
					AccommodatingRec currentRec=(AccommodatingRec)itr2.next();
					days+=(currentRec.getTimeTo().getTime()-currentRec.getTimeFrom().getTime())/86400;
				}
				col.add(days);
				col.add(price*days);
			}
			
			col.add(temp.getPrice());
		}
	}
}
